package com.cyou.qb.admin.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.cyou.qb.service.UploadService;

@Controller
@RequestMapping(value = "/fileUploadSimple")
public class FileUploadSimpleController extends BaseController{
	private Log log =LogFactory.getLog(getClass());
	
	@Autowired
	UploadService uploadService;
	
	@RequestMapping(value = "/form")
	public String form(){
		return "simple/fileuploadsimple";
	}
	@RequestMapping(value = "/ajaxForm")
	public String ajaxForm(){
		return "simple/ajaxFileUpload";
	}
	@RequestMapping(value = "/upload")
	public String upload(@RequestParam("name") String name,@RequestParam("file") MultipartFile file,HttpServletRequest req) throws IOException{
		Assert.hasText(name);
		
		if(file.getBytes().length>100*1000){
			throw new RuntimeException("文件大小不能超过100k");
		}
		try {
			String visitUrl = uploadService.uploadFile(file.getBytes(), file.getOriginalFilename(), 100);
			req.setAttribute("visitUrl", visitUrl);
		} catch (Exception e) {
			log.error("图片上传出错",e);
			throw new RuntimeException("图片上传出错",e);
		}
	
		return "simple/fileuploadsimple";
	}
	
	
	@RequestMapping(value = "/ajaxUpload")
	public String ajaxUpload(@RequestParam(value="image1",required =false) MultipartFile image1,HttpServletRequest req,HttpServletResponse response) throws IOException{
		if(image1.getBytes().length>100*1000){
			throw new RuntimeException("文件大小不能超过100k");
		}
		try {
			String visitUrl = uploadService.uploadFile(image1.getBytes(), image1.getOriginalFilename(), 100);
			print(response, visitUrl);
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("上传出错", e);
			print(response, "error:" + e.getMessage());
		}
		return null;
	}
	
	
}
